﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace UDPHelper
{
    public static class UDPPackageHelper
    {
        /// <summary>
        /// 获取消息包
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="remote_point"></param>
        /// <returns></returns>
        public static UDPPackage GetPackage(byte[] bytes, IPEndPoint remote_point)
        {
            UDPPackage package = new UDPPackage();

            StreamReader sr = new StreamReader(new MemoryStream(bytes), Encoding.UTF8);

            Dictionary<string, string> hearder = new Dictionary<string, string>();

            string line = string.Empty;
            while (!string.IsNullOrEmpty(line = sr.ReadLine()))
            {
                var index = line.IndexOf(':');

                if (index > 0)
                    hearder.Add(line.Substring(0, index), line.Substring(index + 1, line.Length - index - 1));
            }

            package.Body = sr.ReadToEnd();
            package.Header = hearder;
            package.IPAddress = remote_point.Address;
            package.Port = remote_point.Port;

            sr.Close();
            return package;
        }

        public static void SetUrl(UDPPackage package, string url)
        {
            Uri uri = new Uri(url);
            SetHeader(package, "Host", uri.Host);
            SetHeader(package, "Port", uri.Port.ToString());
            SetHeader(package, "Scheme", uri.Scheme);
            SetHeader(package, "Action", uri.AbsolutePath.TrimStart(new[] { '/' }));
        }

        /// <summary>
        /// 获取Body的文本类型数据
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        private static string GetBody(object body)
        {
            if (body == null)
                return string.Empty;

            if (body is string)
                return body as string;

            if (body.GetType().IsValueType)
                return body.ToString();

            return JsonConvert.SerializeObject(body);
        }

        /// <summary>
        /// 获取消息包的序列化内容
        /// </summary>
        /// <param name="package"></param>
        /// <returns></returns>
        public static byte[] GetBytes(UDPPackage package)
        {
            StringBuilder sb = new StringBuilder();
            //sb.AppendLine(string.Format("Host:{0}", package.IPAddress));
            //sb.AppendLine(string.Format("Port:{0}", package.Port));
            foreach (var item in package.Header ?? new Dictionary<string, string>())
            {
                sb.AppendLine(string.Format("{0}:{1}", item.Key, item.Value));
            }

            sb.AppendLine();
            sb.Append(GetBody(package.Body));

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        /// <summary>
        /// 获取请求头
        /// </summary>
        /// <param name="package"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetHeader(UDPPackage package, string key)
        {
            if (package == null)
                return string.Empty;

            return package.Header != null && package.Header.ContainsKey(key) ? package.Header[key] : string.Empty;
        }

        /// <summary>
        /// 设置包头
        /// </summary>
        /// <param name="package"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetHeader(UDPPackage package, string key, string value)
        {
            if (package == null)
                return;

            if (package.Header == null)
                package.Header = new Dictionary<string, string>();

            package.Header[key] = value;
        }
    }
}
